﻿using AutoMapper;
using BasicInformation.ApiWrite.Application.Command.Product;
using BasicInformation.Domain;
using BasicInformation.ErrorCode;
using BasicInformation.Infrastructure.Implement;
using MediatR;

namespace BasicInformation.ApiWrite.Application.Handler.Product
{
    public class AddProductHandler : IRequestHandler<AddProductCommand, ApiResult<int>>
    {
        private readonly DatabaseContext db;
        private readonly ILogger<AddProductHandler> logger;
        private readonly IMapper mapper;

        public AddProductHandler(DatabaseContext db, ILogger<AddProductHandler> logger, IMapper mapper)
        {
            this.db = db;
            this.logger = logger;
            this.mapper = mapper;
        }
        public async Task<ApiResult<int>> Handle(AddProductCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> result = new ApiResult<int>();
            var product = mapper.Map<ProductModel>(request);
            var model = db.SqlSugar.Queryable<ProductModel>().Where(x => x.ProductCode == request.ProductCode).Count();
            if (model > 0)
            {
                result.Msg = "该产品管理信息已存在，请重新输入";
                result.Code = ApiEnum.Fail;
                logger.LogError(result.Msg);
                return await Task.FromResult(result);
            }
            int r = await db.SqlSugar.Insertable(product).ExecuteCommandAsync();
            if (r > 0)
            {
                result.Msg = "产品管理添加成功";
                result.Data = r;
                result.Code = ApiEnum.OK;
                logger.LogInformation(result.Msg);
            }
            else
            {
                result.Msg = "产品管理添加失败";
                result.Data = r;
                result.Code = ApiEnum.Fail;
                logger.LogError(result.Msg);
            }
            return await Task.FromResult(result);
        }
    }
}
